package com.heima.search.listener;

import com.alibaba.fastjson.JSON;
import com.heima.common.constants.message.ArticleForEsConstants;
import com.heima.feigns.article.ArticleFeign;
import com.heima.model.search.vos.SearchArticleVo;
import com.heima.search.service.ArticleSearchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.util.Map;

@Slf4j
@Component
public class ArticleAddOrRemoveListener {
    @Autowired
    ArticleSearchService articleSearchService;
    @Autowired
    ArticleFeign articleFeign;

    @KafkaListener(topics = ArticleForEsConstants.ARTICLE_ELASTICSEARCH_ADD)
    public void addArticle(String msg){
        Map map = JSON.parseObject(msg, Map.class);
        String articleId = map.get("articleId").toString();
        log.info("收到添加es数据库数据请求 文章id为=====> {}",articleId);
        //根据文章id查询搜索的文章
        SearchArticleVo article = articleFeign.findArticle(Long.valueOf(articleId));
        articleSearchService.saveArticle(articleId,article);
    }

    @KafkaListener(topics = ArticleForEsConstants.ARTICLE_ELASTICSEARCH_DELETE)
    public void removeArticle(String msg){
        Map map = JSON.parseObject(msg, Map.class);
        String articleId = map.get("articleId").toString();
        log.info("收到删除es数据库数据请求 文章id为=====> {}",articleId);
        articleSearchService.deleteArticle(articleId);
    }
}
